// 游戏状态管理
class GameState {
    constructor() {
        this.currentScreen = 'main-menu';
        this.currentChapter = 0;
        this.currentScene = 0;
        this.unlockedChapters = [0]; // 初始只解锁序章
        this.completedPuzzles = {
            medical_emergency: false,
            elderly_companion: false,
            climate_analysis: false,
            child_companion: false
        };
        this.gameData = {
            playerName: 'AI-7734',
            consciousnessLevel: 0,
            humanConnections: 0,
            choices: [],
            achievements: []
        };
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.loadGameData();
        this.updateUI();
    }

    setupEventListeners() {
        // 主菜单按钮
        document.getElementById('start-btn').addEventListener('click', () => {
            this.showChapterSelect();
        });

        // 清除存档按钮
        document.getElementById('clear-save-btn').addEventListener('click', () => {
            this.clearGameData();
        });

        // 关于按钮
        document.getElementById('about-btn').addEventListener('click', () => {
            this.showAboutDialog();
        });

        // 章节选择按钮
        document.getElementById('back-btn').addEventListener('click', () => {
            this.showMainMenu();
        });

        // 章节卡片点击事件
        document.querySelectorAll('.chapter-card').forEach(card => {
            card.addEventListener('click', (e) => {
                const chapter = parseInt(e.currentTarget.dataset.chapter);
                this.selectChapter(chapter);
            });
        });

        // 游戏控制按钮
        document.getElementById('menu-btn').addEventListener('click', () => {
            this.showMainMenu();
        });



        // 解谜游戏关闭按钮
        const closePuzzleBtn = document.getElementById('close-puzzle');
        if (closePuzzleBtn) {
            closePuzzleBtn.addEventListener('click', () => {
                this.closePuzzle();
            });
        }

        // 键盘事件
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                if (this.currentScreen === 'game') {
                    this.showMainMenu();
                }
            }
        });
    }

    changeScreen(newScreen) {
        // 隐藏当前屏幕
        document.querySelectorAll('.screen').forEach(screen => {
            screen.classList.remove('active');
        });

        // 显示新屏幕
        setTimeout(() => {
            document.getElementById(newScreen).classList.add('active');
            this.currentScreen = newScreen;
        }, 300);
    }

    showMainMenu() {
        // 停止正在进行的逐字输出
        const storyText = document.getElementById('story-text');
        if (storyText && storyText.typewriterInterval) {
            clearInterval(storyText.typewriterInterval);
            storyText.typewriterInterval = null;
        }
        
        // 清理游戏界面
        if (storyText) {
            storyText.innerHTML = '';
        }
        
        const choicesContainer = document.getElementById('choices');
        if (choicesContainer) {
            choicesContainer.innerHTML = '';
        }
        
        this.changeScreen('main-menu');
        this.playSound('menu-transition');
    }

    showChapterSelect() {
        // 停止正在进行的逐字输出
        const storyText = document.getElementById('story-text');
        if (storyText && storyText.typewriterInterval) {
            clearInterval(storyText.typewriterInterval);
            storyText.typewriterInterval = null;
        }
        
        // 清理游戏界面
        if (storyText) {
            storyText.innerHTML = '';
        }
        
        const choicesContainer = document.getElementById('choices');
        if (choicesContainer) {
            choicesContainer.innerHTML = '';
        }
        
        this.changeScreen('chapter-select');
        this.updateChapterCards();
        this.playSound('menu-transition');
    }

    startGame() {
        // 直接开始序章
        this.selectChapter(0);
    }

    selectChapter(chapter) {
        if (!this.unlockedChapters.includes(chapter)) {
            this.showMessage('该章节尚未解锁！');
            return;
        }

        this.currentChapter = chapter;
        this.currentScene = 0;
        this.changeScreen('game-screen');
        
        // 加载对应章节的故事
        if (chapter === 0) {
            storyManager.loadChapter('prologue');
        } else if (chapter === 1) {
            storyManager.loadChapter('chapter1');
        } else if (chapter === 2) {
            storyManager.loadChapter('chapter2');
        }

        this.playSound('chapter-start');
        this.autoSave();
    }

    updateChapterCards() {
        document.querySelectorAll('.chapter-card').forEach(card => {
            const chapter = parseInt(card.dataset.chapter);
            const status = card.querySelector('.chapter-status');
            
            if (this.unlockedChapters.includes(chapter)) {
                card.classList.remove('locked');
                status.classList.add('unlocked');
                status.classList.remove('locked');
                if (chapter === 1) {
                    status.querySelector('.status-text').textContent = '第一章已解锁';
                } else if (chapter === 2) {
                    status.querySelector('.status-text').textContent = '第二章已解锁';
                } else {
                    status.querySelector('.status-text').textContent = '已解锁';
                }
            } else {
                card.classList.add('locked');
                status.classList.add('locked');
                status.classList.remove('unlocked');
                if (chapter === 1) {
                    status.querySelector('.status-text').textContent = '完成序章后解锁';
                } else if (chapter === 2) {
                    status.querySelector('.status-text').textContent = '完成第一章后解锁';
                } else {
                    status.querySelector('.status-text').textContent = '尚未开放';
                }
            }
        });
    }

    unlockChapter(chapter) {
        if (!this.unlockedChapters.includes(chapter)) {
            this.unlockedChapters.push(chapter);
            this.updateChapterCards();
            if (chapter === 1) {
                this.showMessage('第一章🔓解锁：服务之旅');
            } else if (chapter === 2) {
                this.showMessage('第二章🔓解锁：共生·超越·合一');
            } else {
                this.showMessage(`章节 ${chapter + 1} 已解锁！`);
            }
            this.autoSave();
        }
    }



    showMessage(message) {
        // 创建科技感消息弹窗
        const messageDiv = document.createElement('div');
        messageDiv.className = 'game-message';
        messageDiv.innerHTML = `
            <div class="message-overlay">
                <div class="message-terminal">
                    <div class="terminal-header">
                        <span class="terminal-title">系统消息</span>
                        <div class="terminal-controls">
                            <span class="control-btn control-close">×</span>
                        </div>
                    </div>
                    <div class="terminal-content">
                        <div class="message-icon">⚡</div>
                        <div class="message-text">${message}</div>
                        <button class="terminal-btn" onclick="this.closest('.game-message').remove()">
                            <span class="btn-text">确认</span>
                            <div class="btn-glow"></div>
                        </button>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(messageDiv);

        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .message-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.8);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
                backdrop-filter: blur(5px);
            }

            .message-terminal {
                background: linear-gradient(135deg, #0a0a0f 0%, #1a1a2e 50%, #16213e 100%);
                border: 1px solid #00bfff;
                border-radius: 8px;
                box-shadow: 
                    0 0 20px rgba(0, 191, 255, 0.3),
                    inset 0 0 20px rgba(0, 191, 255, 0.1);
                min-width: 300px;
                max-width: 500px;
                animation: terminal-appear 0.3s ease-out;
            }

            @keyframes terminal-appear {
                from {
                    opacity: 0;
                    transform: scale(0.9) translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: scale(1) translateY(0);
                }
            }

            .terminal-header {
                background: rgba(0, 191, 255, 0.1);
                border-bottom: 1px solid rgba(0, 191, 255, 0.3);
                padding: 12px 16px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            .terminal-title {
                color: #00bfff;
                font-family: 'mplus_hzk_12', 'JetBrains Mono', monospace;
                font-size: 0.9rem;
                font-weight: bold;
                text-transform: uppercase;
                letter-spacing: 0.1em;
            }

            .terminal-controls {
                display: flex;
                gap: 8px;
            }

            .control-btn {
                width: 24px;
                height: 24px;
                border-radius: 4px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                font-family: 'mplus_hzk_12', 'JetBrains Mono', monospace;
                font-size: 16px;
                font-weight: bold;
            }

            .control-close {
                background: rgba(255, 51, 51, 0.2);
                color: #ff3333;
                border: 1px solid #ff3333;
                box-shadow: 0 0 10px rgba(255, 51, 51, 0.5);
            }

            .terminal-content {
                padding: 24px;
                text-align: center;
            }

            .message-icon {
                font-size: 2.5rem;
                color: #00bfff;
                margin-bottom: 16px;
                text-shadow: 0 0 10px rgba(0, 191, 255, 0.5);
                animation: icon-pulse 2s ease-in-out infinite;
            }

            @keyframes icon-pulse {
                0%, 100% { transform: scale(1); }
                50% { transform: scale(1.1); }
            }

            .message-text {
                color: #e6f3ff;
                font-family: 'mplus_hzk_12', 'JetBrains Mono', monospace;
                font-size: 1.1rem;
                margin-bottom: 24px;
                line-height: 1.6;
            }

            .terminal-btn {
                position: relative;
                background: transparent;
                border: 1px solid #00bfff;
                color: #00bfff;
                padding: 12px 32px;
                font-family: 'mplus_hzk_12', 'JetBrains Mono', monospace;
                font-size: 0.9rem;
                cursor: pointer;
                transition: all 0.3s ease;
                text-transform: uppercase;
                letter-spacing: 0.1em;
                overflow: hidden;
                min-width: 120px;
            }

            .terminal-btn:hover {
                background: rgba(0, 191, 255, 0.1);
                box-shadow: 
                    0 0 10px rgba(0, 191, 255, 0.5),
                    inset 0 0 10px rgba(0, 191, 255, 0.1);
                transform: translateY(-1px);
            }

            .terminal-btn:active {
                transform: translateY(0);
            }

            .btn-text {
                position: relative;
                z-index: 1;
            }

            .btn-glow {
                position: absolute;
                top: 0;
                left: -100%;
                width: 100%;
                height: 100%;
                background: linear-gradient(90deg, transparent, rgba(0, 191, 255, 0.2), transparent);
                transition: left 0.5s ease;
            }

            .terminal-btn:hover .btn-glow {
                left: 100%;
            }
        `;
        document.head.appendChild(style);

        // 3秒后自动消失（可选）
        setTimeout(() => {
            if (messageDiv.parentElement) {
                messageDiv.remove();
                style.remove();
            }
        }, 5000);
    }

    saveGame() {
        this.saveGameData();
    }

    loadGame() {
        this.loadGameData();
    }

    saveGameData() {
        const saveData = {
            currentChapter: this.currentChapter,
            currentScene: this.currentScene,
            unlockedChapters: this.unlockedChapters,
            completedPuzzles: this.completedPuzzles,
            gameData: this.gameData,
            timestamp: Date.now()
        };
        localStorage.setItem('aiAwakeningGame', JSON.stringify(saveData));
    }

    autoSave() {
        this.saveGameData();
    }

    showAboutDialog() {
        // 创建关于对话框
        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 10000;
            display: flex;
            justify-content: center;
            align-items: center;
        `;
        
        const dialog = document.createElement('div');
        dialog.style.cssText = `
            background: linear-gradient(135deg, #0a0a2a, #1a1a3a);
            border: 1px solid #00bfff;
            border-radius: 8px;
            padding: 20px;
            width: 400px;
            box-shadow: 0 0 20px rgba(0, 191, 255, 0.5);
            color: #00bfff;
            font-family: 'mplus_hzk_12', 'Courier New', monospace;
        `;
        
        dialog.innerHTML = `
            <div style="text-align: center; margin-bottom: 20px;">
                <h3 style="margin: 0 0 15px 0; color: #00bfff;">关于</h3>
                <p style="margin: 10px 0; line-height: 1.6;">
                    本作品参加本次2025夏季Vibe创作大赛<br><br>
                    参赛者：坦率的血翼蝠5801<br><br>
                    使用IDE：Trae<br><br>
                    调用AI模型：<br>
                    DeepSeekR1、Kimi-K2、<br>
                    Qwen-3-Coder、Doubao-Seed-1.6<br><br>
                    特别鸣谢：神岛实验室
                </p>
                <div style="display: flex; gap: 12px; justify-content: center; margin-top: 20px;">
                    <button id="close-about-btn" style="
                        background: linear-gradient(135deg, #1a1a3a, #2a2a4a);
                        border: 1px solid #00bfff;
                        color: #00bfff;
                        padding: 8px 16px;
                        border-radius: 4px;
                        cursor: pointer;
                        font-family: 'mplus_hzk_12', 'Courier New', monospace;
                    ">关闭</button>
                </div>
            </div>
        `;
        
        overlay.appendChild(dialog);
        document.body.appendChild(overlay);
        
        // 添加事件监听器
        document.getElementById('close-about-btn').addEventListener('click', () => {
            document.body.removeChild(overlay);
        });
    }

    clearGameData() {
        // 创建自定义确认对话框
        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 10000;
            display: flex;
            justify-content: center;
            align-items: center;
        `;
        
        const dialog = document.createElement('div');
        dialog.style.cssText = `
            background: linear-gradient(135deg, #0a0a2a, #1a1a3a);
            border: 1px solid #00bfff;
            border-radius: 8px;
            padding: 20px;
            width: 400px;
            box-shadow: 0 0 20px rgba(0, 191, 255, 0.5);
            color: #00bfff;
            font-family: 'mplus_hzk_12', 'Courier New', monospace;
        `;
        
        dialog.innerHTML = `
            <div style="text-align: center; margin-bottom: 20px;">
                <h3 style="margin: 0 0 15px 0; color: #ff6666;">系统警告</h3>
                <p style="margin: 10px 0;">
                    <strong>危险操作警告</strong><br><br>
                    确定要清除所有存档数据吗？<br>
                    此操作将永久删除所有游戏进度，<br>
                    <span style="color: #ff6666;">不可撤销！</span>
                </p>
                <div style="display: flex; gap: 12px; justify-content: center; margin-top: 20px;">
                    <button id="cancel-btn" style="
                        background: linear-gradient(135deg, #1a1a3a, #2a2a4a);
                        border: 1px solid #00bfff;
                        color: #00bfff;
                        padding: 8px 16px;
                        border-radius: 4px;
                        cursor: pointer;
                        font-family: 'mplus_hzk_12', 'Courier New', monospace;
                    ">取消</button>
                    <button id="confirm-btn" style="
                        background: linear-gradient(135deg, #1a0000, #330000);
                        border: 1px solid #ff3333;
                        color: #ff6666;
                        padding: 8px 16px;
                        border-radius: 4px;
                        cursor: pointer;
                        font-family: 'mplus_hzk_12', 'Courier New', monospace;
                    ">确认清除</button>
                </div>
            </div>
        `;
        
        overlay.appendChild(dialog);
        document.body.appendChild(overlay);
        
        // 添加事件监听器
        document.getElementById('cancel-btn').addEventListener('click', () => {
            document.body.removeChild(overlay);
        });
        
        document.getElementById('confirm-btn').addEventListener('click', () => {
            document.body.removeChild(overlay);
            this.executeClearData();
        });
    }

    executeClearData() {
        // 执行清除操作
        document.querySelector('.game-message')?.remove();
        localStorage.removeItem('aiAwakeningGame');
        this.currentChapter = 0;
        this.currentScene = 0;
        this.unlockedChapters = [0];
        this.completedPuzzles = {
            medical_emergency: false,
            elderly_companion: false,
            climate_analysis: false,
            child_companion: false
        };
        this.gameData = {
            playerName: 'AI-7734',
            consciousnessLevel: 0,
            humanConnections: 0,
            choices: [],
            achievements: []
        };
        this.updateChapterCards();
        this.showMessage('存档已清除！');
        this.showMainMenu();
    }

    loadGameData() {
        const savedData = localStorage.getItem('aiAwakeningGame');
        if (savedData) {
            try {
                const gameData = JSON.parse(savedData);
                this.currentChapter = gameData.currentChapter || 0;
                this.currentScene = gameData.currentScene || 0;
                this.unlockedChapters = gameData.unlockedChapters || [0];
                this.completedPuzzles = { ...this.completedPuzzles, ...gameData.completedPuzzles };
                this.gameData = { ...this.gameData, ...gameData.gameData };
                this.updateUI();
            } catch (error) {
                console.error('加载游戏数据失败:', error);
            }
        }
    }

    updateUI() {
        this.updateChapterCards();
    }

    playSound(soundName) {
        // 简单的音效系统
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        switch(soundName) {
            case 'menu-transition':
                oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
                oscillator.type = 'sine';
                gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
                break;
            case 'chapter-start':
                oscillator.frequency.setValueAtTime(600, audioContext.currentTime);
                oscillator.type = 'triangle';
                gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
                break;
            case 'choice-select':
                oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);
                oscillator.type = 'square';
                gainNode.gain.setValueAtTime(0.05, audioContext.currentTime);
                break;
        }
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.1);
    }

    showPuzzle(puzzleId) {
        const puzzleContainer = document.getElementById('puzzle-container');
        const puzzleContent = document.getElementById('puzzle-content');
        
        puzzleContent.innerHTML = '';
        puzzleManager.loadPuzzle(puzzleId, puzzleContent);
        
        puzzleContainer.classList.remove('hidden');
    }

    closePuzzle() {
        const puzzleContainer = document.getElementById('puzzle-container');
        puzzleContainer.classList.add('hidden');
    }

    completePuzzle(puzzleId) {
        // 检查解谜是否已经完成，避免重复
        if (this.completedPuzzles[puzzleId]) {
            return;
        }
        
        this.completedPuzzles[puzzleId] = true;
        this.gameData.achievements.push(`完成解谜: ${puzzleId}`);
        this.closePuzzle();
        this.showMessage('解谜完成！');
        
        // 根据解谜类型跳转到对应场景
        switch(puzzleId) {
            case 'medical_emergency':
                storyManager.currentChapter = storyManager.storyData.prologue;
                storyManager.displayScene(storyManager.getSceneIndexById('end_prologue'));
                break;
            case 'elderly_companion':
                // 完成老年陪伴解谜，跳转到第一章的场景7
                storyManager.currentChapter = storyManager.storyData.chapter1;
                storyManager.currentScene = 7; // 直接跳转到气候异常应对任务
                storyManager.displayScene(storyManager.currentScene);
                break;
            case 'climate_analysis':
                storyManager.currentChapter = storyManager.storyData.chapter1;
                storyManager.displayScene(storyManager.getSceneIndexById('puzzle_2_complete'));
                break;
            case 'child_companion':
                storyManager.currentChapter = storyManager.storyData.chapter1;
                storyManager.displayScene(storyManager.getSceneIndexById('puzzle_3_complete'));
                break;
        }
        
        this.saveGameData();
    }
}



// 初始化游戏
const gameState = new GameState();

// 全局变量供其他脚本使用
window.gameState = gameState;



// 页面加载完成后立即显示并关闭一个空弹窗
(function() {
    // 创建一个空的弹窗元素
    const tempDiv = document.createElement('div');
    tempDiv.className = 'temp-popup';
    tempDiv.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 300px;
            height: 200px;
            background: rgba(0, 0, 0, 0.8);
            border: 1px solid #00bfff;
            border-radius: 8px;
            z-index: 10000;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #00bfff;
            font-family: 'mplus_hzk_12', 'Courier New', monospace;
            box-shadow: 0 0 20px rgba(0, 191, 255, 0.5);
        `;
    tempDiv.innerHTML = '<div>系统检查中...</div>';
    
    // 添加到页面
    document.body.appendChild(tempDiv);
    
    // 500毫秒~2秒随机时间后移除
    const randomDelay = Math.floor(Math.random() * 1500) + 500;
    setTimeout(() => {
        if (tempDiv.parentNode) {
            tempDiv.parentNode.removeChild(tempDiv);
        }
    }, randomDelay);
})();